package com.javafactroy.kunlong.bip.icp.message.dxp.base;

import lombok.Data;
import com.javafactroy.kunlong.bip.icp.message.base.consts.BodyTypeEnum;
import com.javafactroy.kunlong.bip.icp.message.dxp.iface.IMsgBody;

import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.LinkedHashMap;
import java.util.Map;

@Data
//@ToString
public class DxpBody implements IMsgBody, Serializable {
    BodyTypeEnum bodyTypeEnum;
    static Map<String, Integer> mapDefine = new LinkedHashMap<>();
    static Map<String, Object> mapValues = new LinkedHashMap<>();

    byte[] body;
    String sbody;

    public DxpBody() {
        bodyTypeEnum = BodyTypeEnum.text;
    }

    public byte[] encode() {
        if (bodyTypeEnum == BodyTypeEnum.text) {
            if (sbody == null && body != null) {
                try {
                    sbody = new String(body, "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        if (body == null) {
            return null;
        }
        return body;
    }


    public void decode(byte[] buf) {
        this.body = buf;
        if (bodyTypeEnum == BodyTypeEnum.text) {
            try {
                this.sbody = new String(body, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(e);
            }
        }
    }


    public void check() {

    }

    public String toString() {
        return new String(body, Charset.defaultCharset());
    }
}
